package com.smart.common.shiro.config;

import com.smart.common.shiro.realm.UserRealm;
import com.smart.common.shiro.utils.CustomSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class ShiroConfig {
    @Resource
    RedisSessionDAO redisSessionDAO;


    /**
     * 1. 注册自定义Realm
     */
    @Bean
    public UserRealm realm() {
        return new UserRealm();
    }

    /**
     * 2. 配置url过滤器
     * 统一做鉴权，即判断哪些请求路径需要用户登录，哪些请求路径不需要用户登录。
     * 只做鉴权，不做权限控制，因为权限用注解来实现。
     *
     * @return
     */
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition shiroFilterChainDefinition = new DefaultShiroFilterChainDefinition();
        //不需要认证就能访问
        shiroFilterChainDefinition.addPathDefinition("/test/**", "anon");
        shiroFilterChainDefinition.addPathDefinition("/login", "anon");
        shiroFilterChainDefinition.addPathDefinition("/register", "anon");
        shiroFilterChainDefinition.addPathDefinition("/druid/**", "anon");
        //需要认证才能访问的
        shiroFilterChainDefinition.addPathDefinition("/admin/**", "authc");
        shiroFilterChainDefinition.addPathDefinition("/user/**", "authc");
        shiroFilterChainDefinition.addPathDefinition("/api/**", "authc");
        shiroFilterChainDefinition.addPathDefinition("/**", "authc");
        return shiroFilterChainDefinition;
    }

    /**
     * 3 配置security并设置Realm，避免required a bean named 'authorizer' that could not be found.的报错
     *
     * @param realm
     * @return
     */
    @Bean
    public DefaultWebSecurityManager securityManager(UserRealm realm, SessionManager sessionManager, RedisCacheManager redisCacheManager) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        //inject sessionManager
        defaultWebSecurityManager.setSessionManager(sessionManager);
        // inject redisCacheManager
        defaultWebSecurityManager.setCacheManager(redisCacheManager);
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
    }

    //session管理
    @Bean
    public CustomSessionManager sessionManager() {
        CustomSessionManager sessionManager = new CustomSessionManager();
        //设置redisSessionDao
        sessionManager.setSessionDAO(redisSessionDAO);
        //设置session超时时间为1小时(单位毫秒)
        //sessionManager.setGlobalSessionTimeout(3600000);
        sessionManager.setGlobalSessionTimeout(-1);//永不超时
        return sessionManager;
    }

}